package com.mk.cloud.common.service.core;

import act.Act;
import act.apidoc.Description;
import act.validation.NotBlank;
import com.alibaba.fastjson.JSON;
import com.mk.cloud.common.config.AppConfig;
import com.mk.cloud.common.domain.CpUser;
import com.mk.cloud.common.enums.ErrorCode;
import com.mk.cloud.common.enums.GlobalValues;
import com.mk.cloud.common.exception.UserException;
import com.mk.cloud.common.interceptor.cookie.CookieService;
import com.mk.cloud.common.msg.M;
import com.mk.cloud.common.msg.template.MsSmsValidateLogin;
import com.mk.cloud.common.msg.template.MsSmsValidatePwd;
import com.mk.cloud.common.msg.template.MsSmsValidateReg;
import com.mk.cloud.common.util.CookieUtil;
import org.osgl.util.S;import com.mk.cloud.common.util.S2;
import com.mk.cloud.common.util.VerifyCodeUtils;
import org.apache.commons.lang3.StringUtils;
import org.osgl.mvc.annotation.GetAction;
import org.osgl.mvc.result.Result;
import org.osgl.storage.ISObject;
import org.osgl.storage.impl.SObject;
import org.osgl.util.C;
import org.osgl.util.IO;

import javax.inject.Inject;

@SuppressWarnings("unused")
public class VerificationCodeService extends CookieService {
    public static final String KEY_USER_KEY = "user";

    @Inject
    private CpUser.Mapper cpUserMapper;

    /**
     * 图形验证码,30分钟有效
     * 客户端调用过后，通过
     * CookieUtil.getCookie(GlobalValues.COOKIE_KEYPICCODE.value()) 获取缓存的值
     */
    @GetAction("/validateCode.jpegx")
    @Description("通用-验证码-获取图片验证码")
    public Result validatePicCode(String timestamp) {
        String code = VerifyCodeUtils.outputVerifyImage(4);
        Act.cache().put(timestamp,code,10*60);
        CookieUtil.addCookie(GlobalValues.COOKIE_KEYPICCODE.value(), code,context.resp());
        byte[] ba = VerifyCodeUtils.outputImage(100, 36, code);
        ISObject sobj = SObject.of(ba);
        sobj.setAttribute(ISObject.ATTR_FILE_NAME, "validatecode.jpg");
        sobj.setAttribute(ISObject.ATTR_CONTENT_TYPE, "image/jpg");
        return binary(sobj);
    }

    /**
     * 短信验证码,30分钟有效
     * 客户端调用过后，通过
     * CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + phone) 获取缓存的值
     */
    @GetAction("/validateCode.sms")
    @Description("通用-验证码-获取短信验证码")
    public String validateSmsCode(
        @Description("手机号码") String phone) {
        if (S.isBlank(phone)) {
            String userid = me.getUserid();
            UserException.throwIf(S.isBlank(userid), ErrorCode.E201003);
            CpUser cpuser = cpUserMapper.single(userid);
            UserException.throwIf(cpuser == null, "非法用户!");
            phone = cpuser.getPhone();
        }
        UserException.throwIf(Act.cache().get(phone) !=null,"获取频繁,请稍后再试！");
        String code = S2.randomNumberString(4);

        CookieUtil.addCookie(GlobalValues.SMS_CODE.value() + "-" + phone,code, context.resp());
        System.out.println(phone+"---"+code);
        Act.cache().put(phone,code,60);
        String finalPhone = phone;
        M.excute(new MsSmsValidatePwd() {
            @Override public String product() {
                return AppConfig.dayu.title.get();
            }
            @Override public String code() {
                return code;
            }
            @Override public String phone() {
                return finalPhone;
            }
        });
        return JSON.toJSONString(C.Map("code", code, "phone", phone));
    }

    /**
     * 短信验证码,30分钟有效
     * 客户端调用过后，通过
     * CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + phone) 获取缓存的值
     */
    @GetAction("/validateCodeLogin.sms")
    @Description("通用-验证码-获取短信验证码")
    public String validateSmsCodeLogin(
        @Description("手机号码") String phone) {
        String uid = cpUserMapper.selectUserByPhone(phone);
        UserException.throwIf(Act.cache().get(phone) !=null,"获取频繁,请稍后再试！");
        UserException.throwIf(StringUtils.isBlank(uid), ErrorCode.E201005);
        if (S.isBlank(phone)) {
            String userid = me.getUserid();
            UserException.throwIf(S.isBlank(userid), ErrorCode.E201003);
            CpUser cpuser = cpUserMapper.single(userid);
            UserException.throwIf(cpuser == null, "非法用户!");
            phone = cpuser.getPhone();
        }
        String code = S2.randomNumberString(4);

        CookieUtil.addCookie(GlobalValues.SMS_CODE.value() + "-" + phone,code, context.resp());
        System.out.println(phone+"---"+code);
        Act.cache().put(phone,code,60);
        String finalPhone = phone;
        M.excute(new MsSmsValidateLogin() {
            @Override public String product() {
                return AppConfig.dayu.title.get();
            }
            @Override public String code() {
                return code;
            }
            @Override public String phone() {
                return finalPhone;
            }
        });
        return JSON.toJSONString(C.Map("code", code, "phone", phone));
    }

    /**
     * 短信验证码,30分钟有效
     * 客户端调用过后，通过
     * CookieUtil.getCookie(GlobalValues.SMS_CODE.value() + "-" + phone) 获取缓存的值
     */
    @GetAction("/validateCodeReg.sms")
    @Description("通用-验证码-获取短信验证码")
    public String validateSmsCodeReg(
        @Description("手机号码") String phone) {
        UserException.throwIf(Act.cache().get(phone) !=null,"获取频繁,请稍后再试！");
        if (S.isBlank(phone)) {
            String userid = me.getUserid();
            UserException.throwIf(S.isBlank(userid), ErrorCode.E201003);
            CpUser cpuser = cpUserMapper.single(userid);
            UserException.throwIf(cpuser == null, "非法用户!");
            phone = cpuser.getPhone();
        }
        String code = S2.randomNumberString(4);

        CookieUtil.addCookie(GlobalValues.SMS_CODE.value() + "-" + phone,code, context.resp());
        System.out.println(phone+"---"+code);
        Act.cache().put(phone,code,60);
        String finalPhone = phone;
        M.excute(new MsSmsValidateReg() {
            @Override public String product() {
                return AppConfig.dayu.title.get();
            }
            @Override public String code() {
                return code;
            }
            @Override public String phone() {
                return finalPhone;
            }
        });
        return JSON.toJSONString(C.Map("code", code, "phone", phone));
    }

    @GetAction("/validateImgCode.json")
    @Description("通用-验证码-校验图形验证码")
    public Boolean validateImgCode(@NotBlank String codeImg) {
        //region 图形验证码开始验证
        UserException.throwIf(StringUtils.isBlank(codeImg),ErrorCode.E201014);

        String cachedCodeImg = CookieUtil.getCookie(GlobalValues.COOKIE_KEYPICCODE.value(),context);

        UserException.throwIf(!StringUtils.equalsIgnoreCase(cachedCodeImg,codeImg),ErrorCode.E201009);
        return StringUtils.equalsIgnoreCase(cachedCodeImg,codeImg);
        //endregion
    }

}
